import anime from 'animejs/lib/anime.es.js';

export default class AnimeManager {
  private static animations: any[] = [];
  private static timeScale: number = 1;
  private static lastTimestamp: number | null = null;

  public static anime(params: any): any {
    const wrappedParams = this.wrapParams(params);
    const animation = anime(wrappedParams);
    this.animations.push(animation);
    return animation;
  }

  private static wrapParams(params: any): any {
    const originalUpdate = params.update;
    return {
      ...params,
      update: (anim:any) => {
        const now = performance.now();
        if (this.lastTimestamp === null) {
          this.lastTimestamp = now;
        }
        const deltaTime = (now - this.lastTimestamp) * this.timeScale;
        this.lastTimestamp = now;

        // 更新动画进度
        if (anim.duration > 0) {
          anim.currentTime += deltaTime;
          if (anim.currentTime > anim.duration) {
            anim.currentTime = anim.duration;
          }
        }

        // 调用原始的 update 函数
        if (originalUpdate) {
          originalUpdate(anim);
        }
      },
    };
  }

  public static pauseAll(): void {
    this.timeScale = 0;
  }

  public static resumeAll(): void {
    this.timeScale = 1;
    this.lastTimestamp = null;  // 重置时间戳，避免大跳跃
  }

  public static removeAnimation(animation: any): void {
    const index = this.animations.indexOf(animation);
    if (index > -1) {
      this.animations.splice(index, 1);
    }
  }

  public static cleanUp(): void {
    this.animations = this.animations.filter(animation => !animation.completed);
  }
}